# 使用数据库获取token
# 使用 pymysql 的 库进行查询

import hashlib
import json

import redis

from flask import Flask, request, jsonify
import uuid

app = Flask(__name__)

REDIS_POOL = redis.ConnectionPool(host="127.0.0.1",port=6379, password="",encoding="utf-8",max_connections=1000)
TASK_QUEUE = "spider_task_list"
RESULT_QUEUE = "spider_result_dict"

@app.route("/")
def home():
    print("OK")
    return "OK"

@app.route("/result",methods=["GET"])
def result():
    # result?tid=xxxx
    tid = request.args.get("tid")
    if not tid:
        return jsonify({"status": False, "error":"参数错误"})
    conn = redis.Redis(connection_pool=REDIS_POOL)
    sign = conn.hget(RESULT_QUEUE,tid)
    if not sign:
        return jsonify({"status":True,"data":"", "message":"未完成,继续等待"})
    sign_string = sign.decode("utf-8")
    conn.hdel(RESULT_QUEUE,tid)
    return jsonify({"status":True, "data": sign_string})

@app.route("/task", methods=["POST"])
def task():
    """
    请求的URL中需要携带 token:
    request data form {"ordered_string"}
    """

    try:
        ordered_string = request.json.get("ordered_string")
        if not ordered_string:
            return jsonify({"status":False,"data":"参数错误","version": "v5"})

        # 生成任务id
        tid = str(uuid.uuid4())
        # 1: 放入到队列中
        task_dict = {"tid": tid, "data": ordered_string}
        conn = redis.Redis(connection_pool=REDIS_POOL)
        conn.lpush(TASK_QUEUE, json.dumps(task_dict))
        # 2: 给用户返回
        return jsonify({"status": True, "data": tid,"version": "v6", "message":"Process"})
    except:
        return jsonify({"status": False, "data": "未知错误"})


if __name__ == "__main__":
    app.run()
